package com.xtwy.spike.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 类的描述：
 * http://localhost:8090/api/set/initSku
 * http://localhost:8090/api/set/reduceSku
 * http://localhost:8090/api/set/successNum
 * @作者: 侯建军
 * @邮箱: 474177818@qq.com
 * @博客: https://blog.csdn.net/marquis888
 * @创建日期: 2018年12月02日  18:51
 * @版本: v1.0
 * @jdk版本使用: JDK1.8
 */
@RestController
@RequestMapping("/api/set")
public class SetController {
    /**
     * 注入redis模板
     */
    @Autowired
    private StringRedisTemplate redisTemplate;
    //自增, 记录实际卖出的商品数量
    private AtomicInteger successNum = new AtomicInteger(0);

    //初始化sku
    @RequestMapping(value = "/initSku", method = RequestMethod.GET)
    public String initSku() {
        //zset为有序集合
        //添加商品 默认按照score升序排列
        //初始化库存数量为5，其中1为商品ID
        redisTemplate.opsForZSet().add("product", "1", 5);
        //初始化实际卖出的商品数量0
        successNum.set(0);
        return "初始化库存成功";
    }

    /**
     * 加入事务的减少库存方式
     * 会出现超卖情况的减少库存方式
     *
     * @return
     */
    @RequestMapping(value = "/reduceSku", method = RequestMethod.GET)
    public String reduceSku5(String pid) {
        //如果pid为人，返回为1，否则为pid值
        pid = pid == null ? String.valueOf(1) : pid;
        String finalPid = pid;
        //
        List<Object> results = redisTemplate.execute(new SessionCallback<List<Object>>() {
            @Override
            public List<Object> execute(RedisOperations redisOperations) throws DataAccessException {
                String key = "product";
                //添加事务
                redisOperations.watch(key);
                //获取有序集合对象
                ZSetOperations<String, String> kvzSetOperations = redisOperations.opsForZSet();
                //根据id获取 分数
                Object score = kvzSetOperations.score(key, finalPid);
                //
                redisOperations.multi();
                if (score != null && Double.valueOf(score.toString()) > 0) {
                    //计算 id为finalPid的商品数量 减1
//                    incrementScore 元素分数增加
                    kvzSetOperations.incrementScore("product", finalPid, -1);
                }
                return redisOperations.exec();
            }
        });
        if (results != null && results.size() > 0) {
            //获取减少的值
            return "减少库存成功,共减少" + successNum.incrementAndGet();
        }
        return "库存不足";
    }

    /**
     * 抢到的商品数
     *
     * @return
     */
    @RequestMapping(value = "/successNum", method = RequestMethod.GET)
    public String successNum() {
        return "顾客成功抢到的商品数量：" + successNum.get();
    }
}
